package net.cctms.zhishu;

import java.io.File;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.io.Writer;
import java.util.Arrays;
import java.util.List;

//import javax.annotation.Nullable;

import android.app.ActivityManager;
import android.app.Application;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.res.Configuration;
import android.content.res.Resources;
import android.support.multidex.MultiDex;
import android.support.v4.content.LocalBroadcastManager;
import android.text.TextUtils;


import com.alibaba.android.arouter.launcher.ARouter;
import com.nostra13.universalimageloader.cache.disc.impl.UnlimitedDiscCache;
import com.nostra13.universalimageloader.cache.memory.impl.LruMemoryCache;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.ImageLoaderConfiguration;

import net.cctms.zhishu.webAppFramework.manager.AppService;
import net.cctms.zhishu.webAppFramework.manager.ConfigManager;
import net.cctms.zhishu.webAppFramework.net.universalimageloader.OkHttpImageLoader;
import net.cctms.zhishu.webAppFramework.utils.Log;
import net.cctms.zhishu.webAppFramework.utils.StorageUtil;

/**
 * 应用程序入口 Application子类
 */
public class MyApplication extends Application {

    private static final String ACTION = "LIB_LOCAL_ACTION";
    public static MyApplication mApp;
    protected static final String TAG = MyApplication.class.getSimpleName();
    private static Context context;

    public static MyApplication getInstance() {
        return mApp;
    }
    @Override
    protected void attachBaseContext(Context base) {
        super.attachBaseContext(base);
        //解决64k方法数限制
        MultiDex.install(this);
        mApp=this;
        context = getApplicationContext();
        ARouter.openLog();     // 打印日志
        ARouter.openDebug();   // 开启调试模式(如果在InstantRun模式下运行，必须开启调试模式！线上版本需要关闭,否则有安全风险)
        ARouter.init( this ); // 尽可能早，推荐在Application中初始化

    }
    //返回
    public static Context getContextObject(){
        return context;
    }
    // 判断当前进程是否为主进程
    protected final boolean isMainProcess(Context context) {
        int pid = android.os.Process.myPid();
        try {
            ActivityManager mActivityManager = (ActivityManager) context
                    .getSystemService(Context.ACTIVITY_SERVICE);
            for (ActivityManager.RunningAppProcessInfo appProcess : mActivityManager
                    .getRunningAppProcesses()) {
                if (appProcess.pid == pid) {
                    if (appProcess.processName.equalsIgnoreCase(context
                            .getPackageName())) {
                        return true;
                    }
                }
            }
        }catch (Exception e){
            // ignore
        }
        return false;
    }
    private synchronized static void setApp(MyApplication app){
        mApp = app;
    }

    @Override
    public void onCreate() {
        super.onCreate();

        if (!isMainProcess(this)) {
            return;
        }

        //注册本地广播，用于接收App签名校验失败的通知
        registerLacalReceiver();
        //初始化
        //Helper.init();
        setApp(this);

        StorageUtil.init(this);

        setDefaultUncaughtException();

        //创建ImageLoader的配置参数，并初始化。
        File cacheDir = StorageUtil.getImageDir();
        ImageLoaderConfiguration config = new ImageLoaderConfiguration.Builder(this)
                .threadPoolSize(3) // default 3
                .threadPriority(Thread.NORM_PRIORITY - 1) // default
                .denyCacheImageMultipleSizesInMemory()
                .imageDownloader(new OkHttpImageLoader(this))
                .memoryCache(new LruMemoryCache(2 * 1024 * 1024))  //new WeakMemoryCache()
                .memoryCacheSize(2 * 1024 * 1024)
                .memoryCacheSizePercentage(13) // default
                .diskCache(new UnlimitedDiscCache(cacheDir)) // default
                .diskCacheSize(20 * 1024 * 1024)
                .diskCacheFileCount(100)
                .build();
        ImageLoader.getInstance().init(config);



        //启动看荐服务
        startService(new Intent(this, AppService.class));

        //setHotFixUserInfo();

        //initLeakCanary();

    }

    //移动安全库
    private void registerLacalReceiver() {
        LocalBroadcastManager localBroadcastManager = LocalBroadcastManager.getInstance(this);
        IntentFilter filter = new IntentFilter();
        filter.addAction(ACTION);
        CheckSignatureReciver checkSignatureReciver = new CheckSignatureReciver();
        localBroadcastManager.registerReceiver(checkSignatureReciver, filter);
    }

    class CheckSignatureReciver extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {
            if(intent !=null){
                //当App签名校验失败时，会接收到广播，并且checkValidationResult的值为-1 。
                int checkValidationResult = intent.getIntExtra("key_result" ,0);

                /*
                if(checkValidationResult == -1){
                    UEDAgent.trackCustomKVEvent(MyApplication.this, "rsEvent", null, null);
                }
                */
            }
        }
    }




    private static CustomExceptionHandler mCustomExceptionHandler = new CustomExceptionHandler();

    /**
     * 设置异常捕获
     */
    public static void setDefaultUncaughtException(){
        if(ConfigManager.DEBUG_SWITCH){
            Thread.setDefaultUncaughtExceptionHandler(mCustomExceptionHandler);
        }
    }

    /**
     * 打印日志
     */
    static class CustomExceptionHandler implements Thread.UncaughtExceptionHandler {

        private Thread.UncaughtExceptionHandler defaultUEH;

        public CustomExceptionHandler() {
            defaultUEH = Thread.getDefaultUncaughtExceptionHandler();
        }

        public void uncaughtException(Thread t, Throwable e) {
            final Writer result = new StringWriter();
            final PrintWriter printWriter = new PrintWriter(result);
            e.printStackTrace(printWriter);
            String stacktrace = result.toString();
            printWriter.close();
            Log.e("error", "" + stacktrace);
            defaultUEH.uncaughtException(t, e);
        }
    }


    //以下方法设置字体不随系统变化,防止页面出现错乱
    @Override
    public void onConfigurationChanged(Configuration newConfig) {
        if (newConfig.fontScale != 1)//非默认值
            getResources();
        super.onConfigurationChanged(newConfig);
    }

    @Override
    public Resources getResources() {
        Resources res = super.getResources();
        if (res.getConfiguration().fontScale != 1) {//非默认值
            Configuration newConfig = new Configuration();
            newConfig.setToDefaults();//设置默认
            res.updateConfiguration(newConfig, res.getDisplayMetrics());
        }
        return res;
    }


}
